import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { Layout, Menu, Button, Dropdown, Space } from 'antd';
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom'
import { Outlet } from 'react-router-dom/dist';
import HeaderDropdone from './components/HeaderDropdone'


const { Header, Sider, Content } = Layout;

import { getMenuApi } from '../../apis/menu'
export default function Nav() {
  const [collapsed, setCollapsed] = useState(false);
  const [menus, setMenus] = useState([]);
  //默认选中项
  // const [selectedKeys,setSelectedKeys] = useState("")
  const navigate = useNavigate();
  useEffect(() => {
    getMenu();
  }, []);

  //获取菜单列表
  async function getMenu() {
    //获取用户
    const { username } = JSON.parse(localStorage.user);
    const menuRes = await getMenuApi(username);
    // console.log("menuRes", menuRes);
    //过滤之后需要渲染的菜单
    const menus = formatMenus(menuRes[0].children);
    setMenus([...menus]);
    //过滤菜单函数
    function formatMenus(menus) {
      return handleMenus(menus)
      function handleMenus(menus) {
        return menus.map((item, index) => {
          const o = {
            key: item.path,
            label: item.name,
          }

          if (item.children) {
            //如果有children
            o.children = handleMenus(item.children);
          }
          if (item.icon) {
            o.icon = <i className={'iconfont iconfont-' + item.icon} />
          }
          return o;
        })
      }
    }

  }

  //切换菜单
  function changeMenu(params) {
    console.log("params", params.key);
    if (params.key == "/home") {
      params.key = "/nav" + params.key
    }
    // setSelectedKeys(params.key);
    navigate(params.key)
  }
  return (
    <div>
      <Layout>
        <Sider trigger={null} collapsible collapsed={collapsed}>
          <div className="logo" />
          <Menu
            theme="dark"
            mode="inline"
            defaultSelectedKeys={['1']}
            items={menus}
            onClick={changeMenu}
          // selectedKeys={selectedKeys}
          // defaultOpenKeys={selectedKeys}
          />
        </Sider>
        <Layout className="site-layout">
          <Header
            className="site-layout-background"
            style={{
              padding: 0,
            }}
          >
            {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
              className: 'trigger',
              onClick: () => setCollapsed(!collapsed),
            })}
            <HeaderDropdone />
          </Header>
          <Content
            className="site-layout-background"
            style={{
              margin: '24px 16px',
              padding: 24,
              minHeight: 280,
            }}
          >
            <Outlet />
          </Content>
        </Layout>
      </Layout>
    </div>
  )
}